package com.sservice.web.controller.admin;

import com.sservice.common.SameUrlData;
import com.sservice.urp.entity.Permission;
import com.sservice.urp.vo.RolePermissionUnion;
import com.sservice.urp.vo.RoleVo;
import com.sservice.service.service.IPermissionService;
import com.sservice.service.service.IRolePermissionService;
import com.sservice.service.service.IRoleService;
import com.sservice.service.service.ISysLogService;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.urp.entity.Role;
import com.sservice.urp.entity.RolePermission;
import com.sservice.urp.entity.UserRole;
import com.sservice.web.log.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin/role")
public class RoleController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IRoleService comService;
    @Autowired
    private IRolePermissionService dataService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private ISysLogService sysLogService;

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> create(String permissions, String name, String remark, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Role role = new Role();
        role.setName(name);
        role.setDescription(remark);
        int newId = comService.insert(role);

        if (!"".equals(permissions) && permissions != null) {
            String[] ar = permissions.split(",");
            newId = dataService.addBatch(generateRP(ar, role));
        }
        if (newId > 0) {
            sysLogService.log("创建", request, newId, Action.roleType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, newId);
        return res;
    }


    private List generateRP(String[] ar, Role role) {
        List<RolePermission> rp = new ArrayList<RolePermission>();
        for (String item : ar) {
            RolePermission rp_item = new RolePermission();
            rp_item.setPermissionId(Integer.valueOf(item));
            rp_item.setRoleId(role.getId());
            rp.add(rp_item);
        }
        return rp;
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Role arg) {
        arg.setStatus("0");

        UserRole ur = new UserRole();
        ur.setRoleId(arg.getId());
        int res = comService.queryByRoleId(ur);
        if (res > 0) {
            return new BaseResult(false, "该角色下关联用户数据，禁止删除!", 403);
        }
        int service_res = comService.updateByPrimaryKeySelective(arg);
        int del_res = dataService.deleteByRoleId(String.valueOf(arg.getId()));//上
        return new BaseResult(true, service_res);
    }

    /**
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(String permissions, String name, String permissionNames, String remark, String id, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Role role = new Role();
        int newId = 0;
        role.setId(Integer.valueOf(id));
        if (name != null) {
            role.setRoleName(name);
            role.setDescription(remark);
            newId = comService.updateByPrimaryKeySelective(role);
        }
        if (!"".equals(permissions) && permissions != null) {

            int del_res = dataService.deleteByRoleId(id);
            String[] ar = permissions.split(",");
            newId = dataService.addBatch(generateRP(ar, role));
            if (newId > 0) {
                sysLogService.log("修改权限->" + permissionNames, request, Integer.valueOf(id), Action.roleType);
            }
        }

        BaseResult<Integer> res = new BaseResult<Integer>(true, newId);
        return res;
    }

    /***
     * 分页查询
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query() {
        List<RolePermissionUnion> list = comService.queryAllRoleWithPermission();
        ListResult res = new ListResult(true, list);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public ListResult queryList(RoleVo rv) {
        return comService.queryByPage(rv);
    }

    @ResponseBody
    @RequestMapping(value = "/getPermission/{id}", method = RequestMethod.GET)
    public ListResult getPermission(RoleVo rv) {
        return new ListResult(true, permissionService.getPermissionByRoleId(rv.getId()));
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/add/permission", method = RequestMethod.POST)
    public BaseResult addPermission(Permission rv) {
        permissionService.insertSelective(rv);
        List<RolePermission> list = new ArrayList();
        RolePermission rp = new RolePermission();
        rp.setPermissionId(rv.getId());
        rp.setRoleId(3);
        list.add(rp);
        rolePermissionService.addBatch(list);
        return new BaseResult(true, "");
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/update/permission", method = RequestMethod.POST)
    public BaseResult updatePermission(Permission rv) {
        permissionService.updateByPrimaryKeySelective(rv);
        return new BaseResult(true, "");
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ListResult list() {
        List<Role> list = comService.getRoleList(null);
        ListResult res = new ListResult(true, list);
        return res;
    }
}
